// 这个模块是做全局组件注册的模块
import { useIntersectionObserver } from '@vueuse/core'
import XtxSkeleton from '@/components/skeleton/index.vue'
import XtxCarousel from '@/components/carousel/index.vue'
import XtxMore from '@/components/more/index.vue'
import XtxBread from '@/components/bread/index.vue'
import XtxBreadItem from '@/components/bread/item.vue'
import XtxCity from '@/components/city/index.vue'
import XtxNumbox from '@/components/numbox/index.vue'
import XtxButton from '@/components/button/index.vue'
import XtxCheckbox from '@/components/checkbox/index.vue'
import XtxMessage from '@/components/message/index.vue'
import XtxConfirm from '@/components/confirm/index.vue'
import XtxDialog from '@/components/dialog/index.vue'
import XtxSwitch from '@/components/switch/index.vue'
import XtxTabs from '@/components/tabs/index.vue'
import XtxTabsPane from '@/components/tabs/pane.vue'
import defaultImg from '@/assets/images/200.png'
import { App } from 'vue'
export default {
  // App类型是vue提供的实例类型, 开发中不清楚类型是什么,在不影响功能的前提下 any
  install(app: App) {
    app.component(XtxSkeleton.name, XtxSkeleton)
    app.component(XtxCarousel.name, XtxCarousel)
    app.component(XtxMore.name, XtxMore)
    app.component(XtxBread.name, XtxBread)
    app.component(XtxBreadItem.name, XtxBreadItem)
    app.component(XtxCity.name, XtxCity)
    app.component(XtxNumbox.name, XtxNumbox)
    app.component(XtxButton.name, XtxButton)
    app.component(XtxCheckbox.name, XtxCheckbox)
    app.component(XtxMessage.name, XtxMessage)
    app.component(XtxConfirm.name, XtxConfirm)
    app.component(XtxDialog.name, XtxDialog)
    app.component(XtxSwitch.name, XtxSwitch)
    app.component(XtxTabs.name, XtxTabs)
    app.component(XtxTabsPane.name, XtxTabsPane)
    app.directive('lazy', {
      // vue2中自定指令钩子inserted, 但是在vue3中叫mounted
      mounted(el, binding) {
        // console.log(el) // dom元素
        // console.log(binding.value) // 是指令的信息对象, value属性是指定的值 图片的地址
        // 如果滚到到了可视区, 再为图片赋值
        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }]) => {
            if (isIntersecting) {
              el.src = binding.value
              // 如果图片加载失败 展示默认图片
              el.onerror = () => {
                el.src = defaultImg
              }
              // 进入可视区赋值完毕后 拆解掉滚动监听
              stop()
            }
          },
          {
            // 参数3中有 threshold 临界值属性值是0-1, 0 表示看到及时赋值 1 完整看到再赋值, 默认值不是0  是0.x
            // 值越大 图片赋值越晚
            threshold: 0,
          }
        )
      },
    })
  },
}
